package com.mrazola;

import java.util.Random;

import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class RandomStarsActivity extends Activity {

	static final int STAR_RADIUS = 2;
	static final int STAR_COUNT = 1200;
	SurfaceView ether;
	SurfaceHolder universe;
	Thread painter;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		ether = (SurfaceView) findViewById(R.id.ether);
		universe = ether.getHolder();
		universe.addCallback(new SurfaceHolder.Callback() {

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				painter.interrupt();
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				
				painter = new Thread(new StarPainter());
				painter.start();
			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,
					int height) {
				
			}
		});
	}

	class StarPainter implements Runnable {

		@Override
		public void run() {
			System.out.println("Creando estrellas...");
			int maxWidth = ether.getWidth() - STAR_RADIUS * 2;
			int maxHeight = ether.getHeight() - STAR_RADIUS * 2;
			boolean coloured = false;
			Random randPosition = new Random();
			Random randColor = new Random();
			Paint paint = new Paint();
			int framesOut = 0;
			long begin = System.currentTimeMillis();
			for (int i = 0; i < STAR_COUNT; i++) {
				long start = System.currentTimeMillis();
				int x = randPosition.nextInt(maxWidth) + STAR_RADIUS;
				int y = randPosition.nextInt(maxHeight) + STAR_RADIUS;
				
				if (!coloured) {
					int brightness = randColor.nextInt(255);
					paint.setColor(Color.rgb(brightness, brightness, brightness));
				} else {
					int red = randColor.nextInt(155) +100;//randColor.nextInt(10) >= 5 ? 255 : 0;
					int green = randColor.nextInt(155) +100;//randColor.nextInt(10) >= 5 ? 255 : 0;
					int blue = randColor.nextInt(155) +100;//randColor.nextInt(10) >= 5 ? 255 : 0;
					paint.setColor(Color.rgb(red, green, blue));
				}
				
				Canvas sky = universe.lockCanvas(new Rect(x - STAR_RADIUS, y - STAR_RADIUS, x + STAR_RADIUS, y + STAR_RADIUS));

				sky.drawCircle(x, y, randPosition.nextInt(STAR_RADIUS) + 1, paint);
				
				universe.unlockCanvasAndPost(sky);
				long frame = Math.min(16, System.currentTimeMillis() - start);				
				framesOut += frame >= 16 ? 1 : 0;
				
				try {
					Thread.sleep(16 - frame);
				} catch (InterruptedException e) {
					e.printStackTrace();
					break;
				}
				
			}
			System.out.println(framesOut);
			System.out.println(System.currentTimeMillis() - begin);
		}
		
	}

}